# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""
from optparse import OptionParser
from cve_ease import activate_session, Scraper
from cve_ease.models import SA
from cve_ease.helper import one_instance_check
import logging
import json

logger = logging.getLogger('cve-ease')


def get_usage_str(usage):
    return usage + "\n(Specify the --help global option for a list of other help options)"


def handle_sa(gconfig, db_session, args):
    """[info] OpenEuler security notice info"""

    # one instance
    lock = one_instance_check(gconfig.LOCK_FILE_PATH)
    if lock:
        raise Exception(f"Another cve-ease already running")

    usage = "usage: %prog sa <options>"
    parser = OptionParser(usage=get_usage_str(usage))

    parser.add_option('-r', '--rawdata', dest='raw', action='store_true', default=False,
                      help='get sa cache and print raw data without write db')
    parser.add_option('-m', '--makecache', dest='makecache', action='store_true', default=False,
                      help='get sa cache')
    parser.add_option('-l', '--list', dest='list', action='store_true', default=False,
                      help='list all sa info')
    parser.add_option('-t', '--total', dest='total', action='store_true', default=False,
                      help='get sa info statistics')
    parser.add_option('-v', '--verbose', dest='verbose', action='store_true', default=False,
                      help='show verbose output')

    (options, args) = parser.parse_args(args)

    session = activate_session(db_session, gconfig)
    if gconfig.debug:
        print(" * active sql session")

    if options.makecache:
        scraper = Scraper()
        response = scraper.scrapySA()
        if "code" in response and response["code"] == 0:
            print(" * scrapy from OpenEuler done")
            totalCount = response["result"]["totalCount"]
            print(" * total record num:", totalCount)
            securityNoticeList = response["result"]["securityNoticeList"]

            # recreate table
            SA.__table__.drop(db_session.get_engine())
            SA.__table__.create(db_session.get_engine())
            session.bulk_insert_mappings(SA, securityNoticeList)
            session.commit()
            print(" * makecache done")
        else:
            print("response error! no usefull info found!")
            print(f"response: {response}")
    elif options.total:
        total = session.query(SA).count()
        print("security notice total record :", total)
        if 0 == total:
            print(" WARNNING: no sa cache found! you should run 'cve-ease sa -m' to cache it.")
    elif options.list:
        securityNoticeList = session.query(SA).all()
        if 0 == len(securityNoticeList):
            print(" WARNNING: no sa cache found! you should run 'cve-ease sa -m' to cache it.")
            return
        if options.verbose:
            SA.pretty_output_title()
            for sa in securityNoticeList:
                sa.simple_output()
        else:
            for sa in securityNoticeList:
                sa.pretty_output()
    elif options.raw:
        scraper = Scraper()
        response = scraper.scrapySA()
        if "code" in response and response["code"] == 0:
            print(" * scrapy from OpenEuler done")
            totalCount = response["result"]["totalCount"]
            print(" * total record num:", totalCount)
            print(json.dumps(response, indent=4))
            print(" * makecache done")
        else:
            print("response error! no usefull info found!")
            print(f"response: {response}")
    else:
        parser.print_help()
